/*
 * Copyright (C) 2015 The Sven Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.core.util;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 作者：helloTan on 15/6/3 16:04
 * 邮箱：hellotanm@gmail.com
 */
public class KTSUtil {

    /**
     * 处理值应用
     *
     * @param params key&value
     * @param value value
     * @return key&value
     */
    public static String handleRefVal(Map<String, String> params, String value) {
        String captureKeyAndConstraint = "\\$\\{([a-zA-Z_0-9.]+)\\}";

        Matcher matcher = Pattern.compile(captureKeyAndConstraint).matcher(
                value);
        while (matcher.find()) {
            String val = matcher.group(1);
            String replaceVal = params.get(val);
            if (replaceVal != null) {
                replaceVal = replaceVal.replaceAll("\\\\", "\\/");
                if (replaceVal != null) {
                    value = value.replaceFirst("\\$\\{" + val + "\\}", replaceVal);
                }
            } else {
                throw new RuntimeException("ref for ${" + val + "} not define!");
            }
        }

        return value;
    }
}
